import { ref } from "vue";
import { useStore } from "vuex";
import { useRouter } from "vue-router";
import { userStateKey } from "@/store/userStore";
import { delaySetRef } from "@/global/utils/reactive-utils";
import { useI18n } from "vue-i18n";
import useStaff from "@/composable/staff";
import { onMounted } from "vue";




export default function useLogin() {
  const {t} = useI18n();
  const router = useRouter();
  const userStore = useStore(userStateKey);
  const isLoginFailedAlertShow = ref(false);
  const loginFailedMessage = ref("");
    const { fetchRemoteLoggedStaffToLocal } = useStaff();

  const onLoginSuccessed = (token: string) => {
    userStore.commit("setToken", token);
    console.log("登录成功", token);
    // 登陆成功后从服务器获取当前登录员工
    fetchRemoteLoggedStaffToLocal().then(staff => {
      router.push("/main");
    }).catch(e => {
      onLoginFailed(`错误：${e}`)
    });
  };

  const onLoginFailed = (err: string) => {
    loginFailedMessage.value = t(`responseCode.${err}`)
    console.log("登陆失败", loginFailedMessage.value);
    isLoginFailedAlertShow.value = true;
    delaySetRef(isLoginFailedAlertShow, false, 3000);
  };

  return { onLoginSuccessed, onLoginFailed, loginFailedMessage, isLoginFailedAlertShow };
}
